using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Vin.Extension.JwtBearer.Extension;
using Vin.Tool.AspNetCore.Extension;

namespace Vin.Extension.JwtBearer.Attributes;

public class VinJwtIsAuthorizeAttribute : Attribute, IAuthorizationFilter
{
    public virtual void OnAuthorization(AuthorizationFilterContext context)
    {
        #region 检查是否需要授权

        // 是否不需要授权
        var noNeedCheck = false;
        if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor)
        {
            noNeedCheck = controllerActionDescriptor.ControllerTypeInfo.GetCustomAttributes(inherit: true)
                              .Any(a => a.GetType() == typeof(AllowAnonymousAttribute)) ||
                          controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
                              .Any(a => a.GetType() == typeof(AllowAnonymousAttribute));
        }

        if (noNeedCheck) return;

        #endregion

        #region 判断是否登录

        // 判断是否登录（有token已授权）
        var user = context.HttpContext.User;
        if (user.Identity?.IsAuthenticated == false)
        {
            context.Unauthorized();
        }

        #endregion
    }
}